#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import sys

# reload(sys)
# sys.setdefaultencoding("utf8")
import random
from hashlib import md5
import json  # 导入json模块
import urllib  # 导入urllib模块
from urllib.request import Request, urlopen, URLError, HTTPError  # 导入urllib2模块


def translate(inputFile, outputFile):
    fin = open(inputFile, 'r')  # 以读的方式打开输入文件
    fout = open(outputFile, 'w')  # 以写的方式代开输出文件
    appid = '2027074000067214'
    secretKey = 'LCgis7L17X56qykeTgB'
    myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    fromLang = 'auto'
    toLang = 'fra'
    salt = random.randint(32761, 65226)
    for eachLine in fin:  # 按行读入文件
        line = eachLine.strip()  # 去除每行首尾可能的空格等
        q = line  # 将读入的每行内容转换成特定的格式进行翻译
        sign = appid + q + str(salt) + secretKey
        m1 = md5()
        m1.update(sign)
        sign = m1.hexdigest()
        myurl = myurl + '?appid=' + appid + '&q=' + urllib.quote(
            q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign
        url = myurl
        try:
            resultPage = urlopen(url)  # 调用百度翻译API进行批量翻译
        except HTTPError as e:
            print('The server couldn\'t fulfill the request.')
            print('Error code: ', e.code)
        except URLError as e:
            print('We failed to reach a server.')
            print('Reason: ', e.reason)
        except Exception as e:
            print('translate error.')
            print(e)
            continue

        resultJason = resultPage.read().decode('utf-8')  # 取得翻译的结果，翻译的结果是json格式
        js = None
        try:
            js = json.loads(resultJason)  # 将json格式的结果转换成Python的字典结构
        except Exception as e:
            print('loads Json error.')
            print(e)
            continue

        key = u"trans_result"
        if key in js:
            dst = js["trans_result"][0]["dst"]  # 取得翻译后的文本结果
            outStr = dst
        else:
            outStr = line  # 如果翻译出错，则输出原来的文本

        fout.write(outStr.strip().encode('utf-8') + '\n')  # 将结果输出

    fin.close()
    fout.close()


# 获取目标文件夹的路径
meragefiledir = os.getcwd() + '\\TFH_Annotated_Dataset'
meragefiledir2 = os.getcwd() + '\\OutFiles'
# 获取当前文件夹中的文件名称列表
filenames = os.listdir(meragefiledir)

# 先遍历文件名  多个txt文章文件
for filename in filenames:
    filepath = meragefiledir + '\\'
    filepath = filepath + filename
    filepath2 = meragefiledir2 + '\\' + filename
    # 遍历单个文件，读取行数
    translate(filepath, filepath2)
